package cn.kgc.shiro;

import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import java.util.Arrays;

/**
 * @author 课工场
 * @date 2024/3/25
 * @description  自定义域对象
 */
public class CustomerRealm extends AuthorizingRealm {

    // 授权方法   当用户访问受限资源时
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("----------------CustomerRealm  doGetAuthorizationInfo------------------");
        String primaryPrincipal = (String) principals.getPrimaryPrincipal();
        System.out.println("primaryPrincipal = " + primaryPrincipal);

        //  TODO  根据用户的身份信息primaryPrincipal 查询数据库    user  role  user_role    RBAC     list

        // 该对象用于封装权限信息  角色  权限字符串     admin   super  customer
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        //simpleAuthorizationInfo.addRole("admin");
        //simpleAuthorizationInfo.addRole("super");
        //simpleAuthorizationInfo.addRole("customer");


        // TODO  根据用户的身份信息primaryPrincipal 查询数据库   user  role  user_role  -> roles  ->role_permission  -> permission
        simpleAuthorizationInfo.addRoles(Arrays.asList("admin","customer"));
        // 添加权限字符串
        simpleAuthorizationInfo.addStringPermission("sys:user:add");
        return simpleAuthorizationInfo;
    }

    // 认证方法   login
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        System.out.println("----------------CustomerRealm  doGetAuthenticationInfo------------------");
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
        String username = usernamePasswordToken.getUsername();

        // TODO  查询数据库   userMapper   ->  user == null

       if ("admin".equals(username)){  // 用户名存在  user   ->  SimpleAuthenticationInfo
           SimpleAuthenticationInfo simpleAuthenticationInfo
                   = new SimpleAuthenticationInfo("admin",
                   "c8af6020a726e562745bcddeb66303ac",
                   ByteSource.Util.bytes("java2323"),   //  声明加密时使用的salt
                   this.getName());
           return simpleAuthenticationInfo;
       }

        return null;
    }
}
